 /*客户端：给服务器发送消息*/

#include <sys/types.h>			/* See NOTES */
#include <sys/socket.h>
#include<stdio.h>
#include<stdlib.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include<string.h>
int main()
{

	//1.创建套接字 socket  
	int clientfd=socket(AF_INET,SOCK_STREAM,0);
	if(clientfd==-1)
	{
		perror("socket fail");
		exit(-1);
	}
	printf("创建socket成功\n");

	
	//2.主动连接服务器的地址IP+端口号 connect
	int res;
	struct sockaddr_in addr;
	memset(&addr,0,sizeof(addr));
	addr.sin_family=AF_INET;
	addr.sin_port=htons(49999);//服务器的端口号
	struct in_addr ip;
	inet_aton("192.168.31.114",&ip);
	addr.sin_addr=ip;//设置服务器ip
	res=connect(clientfd, (struct sockaddr*)&addr,sizeof(addr));
	if(res==-1)
	{
		perror("connect fail");
		exit(-1);
	}
	printf("建立连接成功\n");
	
	//3.往服务器发送消息 write
	while(1)
	{
		char buf[1024]={0};
		fgets(buf,sizeof(buf),stdin);
		res=write(clientfd,buf,strlen(buf));
		if(res==-1)
		{
			perror("write fail");
			exit(-1);
		}
		if(strcmp(buf,"quite\n")==0)
		{
			break;
		}
		printf("发送消息的内容是%s,成功发送的字节数是:%d\n",buf,res);
	}
	
	//4.关闭套接字
	close(clientfd);

	return 0;
}






